use std::{
    borrow::Cow,
    collections::HashMap,
    fmt::{self, Debug, Formatter},
    hash::Hash,
    path::PathBuf,
};

use rust_embed::{EmbeddedFile, Metadata};

use QcCore::resources::ResourceTrait;
use QcRender::resources::Resource;

pub struct Assets {
    path: PathBuf,
    hashmap: HashMap<String, EmbeddedFile>,
}

impl Debug for Assets {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Assets").field("path", &self.path).finish()
    }
}

impl Assets {
    pub fn new(path: PathBuf) -> Assets {
        Self {
            path: path.join("assets"),
            hashmap: HashMap::new(),
        }
    }
}

impl ResourceTrait for Assets {
    fn get(&mut self, file_path: &str) -> Option<Resource> {
        let path = self.path.join(file_path);

        if let Some(data) = self.hashmap.get(file_path) {
            Some(Resource {
                name: file_path.to_owned(),
                file: data.clone(),
            })
        } else {
            println!("没有缓存 {} 文件", path.display());
            if let Ok(file) = rust_embed::utils::read_file_from_fs(&path) {
                self.hashmap.insert(file_path.to_string(), file.clone());
                Some(Resource {
                    name: file_path.to_owned(),
                    file,
                })
            } else {
                None
            }
        }
    }

    fn get_path(&self) -> PathBuf {
        self.path.clone()
    }
}
